import { defineStore } from "pinia";
import { constantRoutes } from "@/router/router";
// 引入类型
import type { LoginFormType, LoginResponseType } from "@/types/userType";
import type { UserState } from "./types/storeType";
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "@/utils/token";
import api from "@/api/index";
const $api = api.user;

const useUserStore = defineStore("userStore", {
  state: (): UserState => {
    return {
      token: GET_TOKEN("TOKEN"),
      menuRoutes: constantRoutes,
      userName: "",
      avatar: "",
      buttons: [],
    };
  },
  actions: {
    // 用户登录
    async userLogin(loginData: LoginFormType) {
      let ret: LoginResponseType = await $api.reqLogin(loginData);
      if (ret.code === 200) {
        SET_TOKEN(ret.data.token as string);
        return "ok";
      } else {
        return Promise.reject(new Error("账号或密码错误"));
      }
    },
    // 获取用户信息
    async userInfo() {
      let ret = await $api.reqUserInfo();
      if (ret.code === 200) {
        this.userName = ret.data.checkUser.userName;
        this.avatar = ret.data.checkUser.avatar;
        this.buttons = ret.data.checkUser.buttons;
        return "ok";
      } else {
        return Promise.reject(new Error("用户信息获取失败"));
      }
    },
    // 退出登录
    async loginOut() {
      // let ret = await
      REMOVE_TOKEN("TOKEN");
      this.userName = "";
      this.avatar = "";
    },
  },
  getters: {},
});

export default useUserStore;
